package c2.group.business.teampvp;

import c2.advanced.business.base.KvData;
import cate.common.util.TimeTool;
import cate.game.rank.po.Rank;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class TeamPvpKv extends KvData {
    public Period period;
    public long nextCheckTime;
    @NoteField("排行榜")
    public List<Rank> ranks;
    public int season;

    @Override
    public void init(String key) {
        super.init(key);
        if (ranks == null) {
            ranks = new ArrayList<>();
        }
        if (period == null && nextCheckTime == 0) {
            period = Period.SLEEP;
            nextCheckTime = TimeTool.getZeroMondayTimeStamp(System.currentTimeMillis()) + period.checkTime;
        }
        if (season == 0) {
            season = 1;
        }
    }

    public void tick (TeamPvpModule parent) {
        long now = System.currentTimeMillis();
        if (now < nextCheckTime) {
            return;
        }
        period = period.getNextPeriod();
        nextCheckTime += period.checkTime;
        if (period == Period.FIGHT) {
            synchronized (ranks) {
                ranks.clear();
            }
        } else if (period == Period.SLEEP) {
            season ++;
            parent.getPool().seasonReset();
            parent.getTeam().seasonReset();
            parent.getInvite().seasonReset();
        } else if (period == Period.SETTLE) {
            parent.getFight().settle();
            parent.getPool().seasonSettle(season);
        }
        log.info("组队竞技切换到period={}, 下次检测时间={}", period, new Date(nextCheckTime));
    }

    public void updateRankList(List<Rank> newRanks) {
        ranks = newRanks;
    }

    public List<Rank> loadRanks() {
        return ranks;
    }

    public List<Rank> loadGods() {
        List<Rank> list = new ArrayList<>(3);
        synchronized (ranks) {
            for (Rank rank : ranks) {
                if (list.size() >= 3) {
                    return list;
                }
                list.add(rank);
            }
        }
        return list;
    }

    public Period getPeriod() {
        return period;
    }

    public int getSeason() {
        return season;
    }

    public enum Period {
        /** 休赛 */
        SLEEP(4 * 24 * 3600 * 1000L),
        /** 组队 */
        TEAM(24 * 3600 * 1000L),
        /** 战斗 */
        FIGHT(2 * 24 * 3600 * 1000L),
        /** 结算 */
        SETTLE(1);

        private long checkTime;

        Period(long checkTime) {
            this.checkTime = checkTime;
        }

        public Period getNextPeriod() {
            if (this == SETTLE) {
                return SLEEP;
            }
            return values()[ordinal() + 1];
        }
    }
}
